package com.xin.data.simbapesa.activity;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;

import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.xin.data.simbapesa.PathMaping;
import com.xin.data.simbapesa.R;
import com.xin.data.simbapesa.api.PU;
import com.xin.data.simbapesa.api.RxHttp;
import com.xin.data.simbapesa.api.U;
import com.xin.data.simbapesa.base.BaseActivity;
import com.xin.data.simbapesa.base.BaseDialog;
import com.xin.data.simbapesa.base.BaseParams;
import com.xin.data.simbapesa.databinding.SimbaOcrActivityBinding;
import com.xin.data.simbapesa.dialog.PhotoDialog;
import com.xin.data.simbapesa.obj.SimbaValueInfo;
import com.xin.data.simbapesa.utils.AESCryptUtilJar;
import com.xin.data.simbapesa.utils.FileUtils;
import com.xin.data.simbapesa.utils.ImgUitls;
import com.xin.data.simbapesa.utils.JsonParse;
import com.xin.data.simbapesa.utils.LogUtil;
import com.xin.data.simbapesa.utils.PopUtils;
import com.xin.data.simbapesa.utils.ResUtils;
import com.xin.data.simbapesa.utils.ViewUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class SimbaOcrActivity extends BaseActivity<SimbaOcrActivityBinding> {


    ActivityResultLauncher<PickVisualMediaRequest> pickMedia;

    private long clickStartTime = 0;

    private long clickEndTime = 0;


    PhotoDialog photoDialog;

    List<SimbaValueInfo> list;

    int mIndex;

    boolean isBack;


    @Override
    protected SimbaOcrActivityBinding initViewBinding(LayoutInflater inflater) {
        return SimbaOcrActivityBinding.inflate(inflater);
    }

    @Override
    protected void initView() {

        binding.getRoot().setPadding(0, 0, 0, 0);
        setStatusBarHeight2(binding.tvRoot, ResUtils.d(R.dimen.dp_12), ResUtils.d(R.dimen.dp_12), ResUtils.d(R.dimen.dp_12));

        binding.tvHit1.setText(Html.fromHtml(ResUtils.s(R.string.ocr_hit1)));
        binding.tvBox.setSelected(true);


        list = new ArrayList<>();

        SimbaValueInfo valueInfo1 = new SimbaValueInfo();
        valueInfo1.setTitle(ResUtils.s(R.string.ocr_type1));
        valueInfo1.setValue("IDCARD");

        SimbaValueInfo valueInfo2 = new SimbaValueInfo();
        valueInfo2.setTitle(ResUtils.s(R.string.ocr_type2));
        valueInfo2.setValue("PASSPORT");

        SimbaValueInfo valueInfo3 = new SimbaValueInfo();
        valueInfo3.setTitle(ResUtils.s(R.string.ocr_type3));
        valueInfo3.setValue("DRIVING");

        SimbaValueInfo valueInfo4 = new SimbaValueInfo();
        valueInfo4.setTitle(ResUtils.s(R.string.ocr_type4));
        valueInfo4.setValue("DRIVING");

        list.add(valueInfo1);
        list.add(valueInfo2);
        list.add(valueInfo3);
        list.add(valueInfo4);

        binding.tvTypeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewUtils.viewScale(v);
                PopUtils.showSelectPop(getActivity(), binding.tvType, list, binding.tvType.getText().toString(), 0, 0, new PopUtils.PopClickInterface() {
                    @Override
                    public void onClickListener(String title, String value, int position, int index) {
                        mIndex = index;
                        binding.tvType.setText(title);
                        switchTab();
                    }
                });

            }
        });

        binding.frontLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewUtils.viewScale(v);
                isBack = false;
                showPhotoDialog();
            }
        });

        binding.backLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewUtils.viewScale(v);
                isBack = true;
                showPhotoDialog();
            }
        });

        binding.tvBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewUtils.viewScale(v);
                PU.userBuriedPoint(PU.P196, "");
                PU.userBuriedAllPoint(getActivity());
                ocrInfo();
            }
        });

        binding.tvHitLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewUtils.viewScale(v);
                binding.tvBox.setSelected(!binding.tvBox.isSelected());
            }
        });

        binding.tvBk.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            finish();
        });
        binding.tvCs.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            startActivity(new Intent(getActivity(), SimbaCustomerServiceActivity.class));
        });

    }

    @Override
    protected void initData() {
        UP_TYPE1 = PU.P119;
        UP_TYPE2 = PU.P120;
        pickMedia = registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {
            if (uri != null) {
                String imgPath = FileUtils.getFileAbsolutePath(getActivity(), uri);
                imageUpload(uri, imgPath);
                LogUtil.e("me", "imgPath->" + imgPath);
                clickEndTime = System.currentTimeMillis();
                PU.userBuriedPoint(PU.P128, imgPath + "$$" + (clickEndTime - clickStartTime));
            }
        });

    }

    void switchTab() {


        binding.tvHit1.setVisibility(View.VISIBLE);

        SimbaValueInfo valueInfo = list.get(mIndex);

        if (valueInfo != null) {
            valueInfo.setValue1("");
            valueInfo.setValue2("");
        }

        if (mIndex == 1) {

            binding.frontLayout.setVisibility(View.VISIBLE);
            binding.backLayout.setVisibility(View.GONE);


            binding.frontImg.setImageResource(R.mipmap.ocr_front_img);

            binding.frontImgTxt.setText(ResUtils.s(R.string.ocr_btn1));


            binding.frontImgCover.setVisibility(View.GONE);


            PU.userBuriedPoint(PU.P124, "");


        } else if (mIndex == 0) {


            binding.frontLayout.setVisibility(View.VISIBLE);
            binding.backLayout.setVisibility(View.VISIBLE);

            binding.frontPhoto.setVisibility(View.VISIBLE);
            binding.frontImg.setImageResource(R.mipmap.ocr_front_img);
            binding.backPhoto.setVisibility(View.VISIBLE);
            binding.backImg.setImageResource(R.mipmap.ocr_back_img);


            binding.frontImgTxt.setText(ResUtils.s(R.string.ocr_btn1));
            binding.backImgTxt.setText(ResUtils.s(R.string.ocr_btn1));


            binding.frontImgCover.setVisibility(View.GONE);
            binding.backImgCover.setVisibility(View.GONE);


            PU.userBuriedPoint(PU.P122, "");


        } else if (mIndex == 2) {

            binding.frontLayout.setVisibility(View.VISIBLE);
            binding.backLayout.setVisibility(View.VISIBLE);

            binding.frontPhoto.setVisibility(View.VISIBLE);
            binding.frontImg.setImageResource(R.mipmap.ocr_front_img);
            binding.backPhoto.setVisibility(View.VISIBLE);
            binding.backImg.setImageResource(R.mipmap.ocr_back_img);


            binding.frontImgTxt.setText(ResUtils.s(R.string.ocr_btn1));
            binding.backImgTxt.setText(ResUtils.s(R.string.ocr_btn1));


            binding.frontImgCover.setVisibility(View.GONE);
            binding.backImgCover.setVisibility(View.GONE);

            PU.userBuriedPoint(PU.P123, "");

        } else if (mIndex == 3) {

            binding.frontLayout.setVisibility(View.VISIBLE);
            binding.backLayout.setVisibility(View.VISIBLE);

            binding.frontPhoto.setVisibility(View.VISIBLE);
            binding.frontImg.setImageResource(R.mipmap.ocr_front_img);
            binding.backPhoto.setVisibility(View.VISIBLE);
            binding.backImg.setImageResource(R.mipmap.ocr_back_img);


            binding.frontImgTxt.setText(ResUtils.s(R.string.ocr_btn1));
            binding.backImgTxt.setText(ResUtils.s(R.string.ocr_btn1));


            binding.frontImgCover.setVisibility(View.GONE);
            binding.backImgCover.setVisibility(View.GONE);


            PU.userBuriedPoint(PU.P125, "");

        }

        binding.frontPhoto.setImageResource(R.mipmap.ocr_upload);
        binding.backPhoto.setImageResource(R.mipmap.ocr_upload);
        binding.frontImgTxt.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
        binding.backImgTxt.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);

    }

    void loadData(String url) {

        if (getActivity() != null && !isFinishing()) {


            LogUtil.e("me", url + "<-position->" + mIndex);

            SimbaValueInfo valueInfo = list.get(mIndex);

            if (valueInfo == null) {
                return;
            }

            if (!TextUtils.isEmpty(url)) {
                if (mIndex == 1) {
                    valueInfo.setValue1(url);
                    Glide.with(getActivity()).load(url).placeholder(R.color.placeholder_icon).into(binding.frontImg);
                    binding.frontPhoto.setVisibility(View.GONE);
                    binding.frontImgCover.setVisibility(View.VISIBLE);
                    binding.frontImgTxt.setText(ResUtils.s(R.string.ocr_btn2));
                    binding.frontImgTxt.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.ocr_reset, 0, 0);
                    binding.frontImgTxt.setTextColor(Color.parseColor("#FFFFFF"));
                } else {

                    if (isBack) {
                        valueInfo.setValue2(url);
                        binding.backPhoto.setVisibility(View.GONE);
                        Glide.with(getActivity()).load(url).placeholder(R.color.placeholder_icon).into(binding.backImg);
                        binding.backImgCover.setVisibility(View.VISIBLE);
                        binding.backImgTxt.setText(ResUtils.s(R.string.ocr_btn2));
                        binding.backImgTxt.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.ocr_reset, 0, 0);
                        binding.backImgTxt.setTextColor(Color.parseColor("#FFFFFF"));
                    } else {
                        valueInfo.setValue1(url);
                        binding.frontPhoto.setVisibility(View.GONE);
                        Glide.with(getActivity()).load(url).placeholder(R.color.placeholder_icon).into(binding.frontImg);
                        binding.frontImgCover.setVisibility(View.VISIBLE);
                        binding.frontImgTxt.setText(ResUtils.s(R.string.ocr_btn2));
                        binding.frontImgTxt.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.ocr_reset, 0, 0);
                        binding.frontImgTxt.setTextColor(Color.parseColor("#FFFFFF"));
                    }


                }
            }

        }
    }

    void showPhotoDialog() {
        if (photoDialog == null) {
            photoDialog = new PhotoDialog(this);
        }
        photoDialog.setOnBtnClickListener(new BaseDialog.BtnClickListener() {
            @Override
            public void btnOnClickOk() {
                int type = photoDialog.getType();
                if (type == 1) {
                    toTakePhoto();
                } else if (type == 2) {
                    formAlbum();
                }
            }

            @Override
            public void btnOnClickCancel() {

            }

            @Override
            public void btnOnClickColse() {

            }
        });
        photoDialog.show();
    }

    void toTakePhoto() {
        clickStartTime = System.currentTimeMillis();
        Intent intent = new Intent(this, SimbaCameraActivity.class);
        someActivityResultLauncher.launch(intent);
    }


    void formAlbum() {
        clickStartTime = System.currentTimeMillis();
        if (pickMedia != null) {
            pickMedia.launch(new PickVisualMediaRequest.Builder()
                    .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                    .build());
        }
    }

    final ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                LogUtil.e("me", "--onActivityResult--");
                if (result.getResultCode() == RESULT_OK) {
                    Intent data = result.getData();
                    if (data != null) {
                        String url = data.getStringExtra("url");
                        LogUtil.e("me", "onActivityResult url->" + url);
                        if (!TextUtils.isEmpty(url)) {
                            loadData(url);
                        }
                        PU.userBuriedPoint(PU.P127, url + "$$" + (clickEndTime - clickStartTime));
                    }
                }
            }
    );


    void ocrInfo() {

        String faceImgUrl;
        String cardImgUrl;
        String cardBackImgUrl;
        String cardType;
        if (mIndex != 4) {

            SimbaValueInfo valueInfo = null;

            if (mIndex < list.size()) {
                valueInfo = list.get(mIndex);
            }

            if (valueInfo == null) {
                showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.ocr_tips1));
                return;
            }
            faceImgUrl = valueInfo.getValue3();
            cardImgUrl = valueInfo.getValue1();
            cardBackImgUrl = valueInfo.getValue2();
            cardType = valueInfo.getValue();

            LogUtil.e("me", cardBackImgUrl + "--ocrInfo--" + isBack + "," + cardImgUrl);

            if ((cardType.equals("IDCARD") || cardType.equals("DRIVING")) && TextUtils.isEmpty(cardImgUrl)) {
                showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.ocr_tips2));
                return;
            }
            if ((cardType.equals("IDCARD") || cardType.equals("DRIVING")) && TextUtils.isEmpty(cardBackImgUrl)) {
                showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.ocr_tips3));
                return;
            }
            if (cardType.equals("PASSPORT") && TextUtils.isEmpty(cardImgUrl)) {
                showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.ocr_tips2));
                return;
            }

            if (cardType.equals("FACE") && TextUtils.isEmpty(faceImgUrl)) {
                showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.ocr_tips4));
                return;
            }
        } else {
            faceImgUrl = "https://test.png";
            cardImgUrl = "https://test.png";
            cardBackImgUrl = "https://test.png";
            cardType = "IDCARD";
        }
        showLoading("");
        JsonObject json = BaseParams.getJsonObject(getActivity(), PathMaping.PathList[53]);
        json.addProperty("cardType", cardType);
        json.addProperty("faceImgUrl", faceImgUrl);
        json.addProperty("cardImgUrl", cardImgUrl);
        json.addProperty("cardBackImgUrl", cardBackImgUrl);


        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_COUNTRY);
        }

        String data = AESCryptUtilJar.encryptDefault(json.toString());

        LogUtil.e("me", json + "<-ocrInfo post->" + data);

        RxHttp.post(U.commonUrl, data, heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                        if (binding != null) {
                            hideLoading();
                            if (!TextUtils.isEmpty(s)) {
                                String json1 = AESCryptUtilJar.decryptDefault(s);
                                if (JsonParse.getCode(json1)) {
                                    String token = JsonParse.ocrInfoJson2Obj(json1);
                                    LogUtil.e("me", "ocrInfo json->" + token);
                                    if (!TextUtils.isEmpty(token)) {
                                        userProcess(() -> {
                                            if (binding.tvBox.isSelected() && mIndex != 4) {
                                                Toast.makeText(getActivity(), getResources().getString(R.string.ocr_tips5), Toast.LENGTH_LONG).show();
                                            }
                                            boolean isCheckSteps = checkSteps();
                                            if (!isCheckSteps) {
                                                startActivity(new Intent(getActivity(), SimbaApplyActivity.class));
                                            }
                                            finish();
                                        }, true);
                                    }
                                } else {
                                    showToastDialog(R.mipmap.hit_icon, JsonParse.getMsg(getActivity(), json1));
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        if (binding != null) {
                            hideLoading();
                            showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.start_net_failed));
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    void imageUpload(Uri imageUri, String path) {
        showLoading(ResUtils.s(R.string.upload));
        LogUtil.e("me", "URL.uploadUrl->" + U.uploadUrl);
        RxHttp.uploadImage(U.uploadUrl, ImgUitls.compressToTargetSize(this, imageUri, 1024, path))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                        hideLoading();
                        if (!TextUtils.isEmpty(s)) {
                            String url = JsonParse.imageUploadJson2Obj(s);
                            LogUtil.e("me", "imageUpload url->" + url);
                            if (!TextUtils.isEmpty(url)) {
                                showToastDialog(R.mipmap.hit_icon2, ResUtils.s(R.string.upload_completed));
                                loadData(url);
                            }
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        if (e != null) {
                            LogUtil.e("me", "imageUpload e->" + e);
                        }
                        hideLoading();
                        showToastDialog(R.mipmap.hit_icon, ResUtils.s(R.string.upload_failed));
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (photoDialog != null) {
            photoDialog.dismiss();
        }
    }


}
